package com.ktjy.examination.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjy.examination.entity.Book;
import com.ktjy.examination.mapper.BookMapper;
import com.ktjy.examination.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BookServiceImpl implements BookService {
    @Resource
    private BookMapper bookMapper;

    @Override
    public IPage<Book> findPageVo(Integer bookType, String bookName, Integer isBorrowed, Integer pageNo, Integer pageSize) {
        Page<Book> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

        // 构建查询条件
        if (bookType != null) {
            queryWrapper.eq("bookType", bookType);
        }
        if (bookName != null && !bookName.trim().isEmpty()) {
            queryWrapper.like("bookName", bookName.trim());
        }
        if (isBorrowed != null) {
            queryWrapper.eq("isBorrowed", isBorrowed);
        }
            // 添加默认排序
            queryWrapper.orderByDesc("lastUpdateTime");

            return bookMapper.selectPage(page, queryWrapper);
        }

    @Override
    public boolean borrowBook(Long bookId) {
        Book book = bookMapper.selectById(bookId);
        if (book == null || book.getIsBorrowed() == 1) {
            return false;
        }
        book.setIsBorrowed(1);
        book.setCount(book.getCount() == null ? 1 : book.getCount() + 1);  // 借阅次数加1
        book.setLastUpdateTime(new Date());
        return bookMapper.updateById(book) > 0;
    }
}